{% extends "base_generic.html" %}

{% block content %}
  <h1>我的收藏</h1>
  {% if book_list %}
  <div class="row">
    {% for book in book_list %}
    <div class="col-md-4 mb-4">
      <div class="card h-100">
        {% if book.cover_image %}
          <img src="{{ book.cover_image.url }}" class="card-img-top" alt="{{ book.title }}" style="height: 300px; object-fit: cover;">
        {% else %}
          <img src="{% static 'images/no-cover.png' %}" class="card-img-top" alt="No cover available" style="height: 300px; object-fit: cover;">
        {% endif %}
        <div class="card-body">
          <h5 class="card-title">{{ book.title }}</h5>
          <p class="card-text">作者: <a href="{{ book.author.get_absolute_url }}">{{ book.author }}</a></p>
          <div class="book-stats mb-2">
            <span class="mr-3">
              <i class="fas fa-star text-warning"></i> {{ book.average_rating|default:"暂无评分" }}
            </span>
            <span class="mr-3">
              <i class="fas fa-heart text-danger"></i> {{ book.likes.count }}
            </span>
            <span>
              <i class="fas fa-bookmark text-primary"></i> {{ book.favorites.count }}
            </span>
          </div>
          {% if book.price %}
          <p class="card-text text-success font-weight-bold">¥{{ book.price }}</p>
          {% endif %}
          <div class="btn-group">
            <a href="{{ book.get_absolute_url }}" class="btn btn-primary">查看详情</a>
            <button class="btn btn-warning remove-favorite" data-book-id="{{ book.id }}">
              <i class="fas fa-bookmark"></i> 取消收藏
            </button>
          </div>
        </div>
      </div>
    </div>
    {% endfor %}
  </div>
  {% else %}
    <p>您还没有收藏任何图书。</p>
  {% endif %}
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('.remove-favorite').forEach(btn => {
    btn.addEventListener('click', function() {
      const bookId = this.dataset.bookId;
      fetch(`/catalog/book/${bookId}/favorite/`, {
        method: 'POST',
        headers: {
          'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
        }
      })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          // 移除整个卡片
          this.closest('.col-md-4').remove();
        }
      });
    });
  });
});
</script>
{% endblock %} 